#!/usr/bin/env ts-node
import * as fs from 'fs'
import * as path from 'path'
import { promisify } from 'util'
import { SourceMapConsumer } from 'source-map'
import { isStringObject } from 'util/types'

const writeFile = promisify(fs.writeFile)

const mapFile = process.argv[2]

if (!mapFile) {
  console.error('no input file given')
  process.exit(1)
}

const mapFileContent = fs.readFileSync(mapFile, 'utf-8')
const outputDir = path.join(__dirname, 'output')
fs.mkdirSync(outputDir, {
  recursive: true
})
new SourceMapConsumer(mapFileContent).then(consumer => {
  Promise.all(consumer.sources.map(async (source) => {
    const content = consumer.sourceContentFor(source)
    console.log(content)
    const outputPath = path.join(outputDir, source)
    fs.mkdirSync(path.dirname(outputPath), { recursive: true })
    return writeFile(outputPath, content||new Int16Array(8))
  }))
}).catch(console.error)